<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="发布时间" prop="createDt">
        <el-date-picker clearable size="small" style="width: 200px"
          v-model="queryParams.createDt"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="选择发布时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="操作员名称" prop="operatorName">
        <el-input
          v-model="queryParams.operatorName"
          placeholder="请输入操作员名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="cyan" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:paper:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:paper:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:paper:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:paper:export']"
        >导出</el-button>
      </el-col>
	  <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="paperList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="名称" align="center" prop="name" />
      <el-table-column label="总分" align="center" prop="score" />
      <el-table-column label="合格分" align="center" prop="standardScore" />
      <el-table-column label="题数" align="center" prop="questionCount" />
      <el-table-column value-format="yyyy-MM-dd" label="发布时间" align="center" prop="createDt" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createDt, '{y}-{m}-{d} {hh}:{mm}:{ss}') }}</span>
        </template>
      </el-table-column>
      <!-- <el-table-column label="进度" align="center" prop="progressCode" /> -->
      <el-table-column
        label="进度"
        align="center"
        prop="progressCode"
        :formatter="collegeStatusFormat"
      />
      <el-table-column label="发布日期" align="center" prop="publishDt" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.publishDt, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="有效时间天数" align="center" prop="validityDay" />
      <el-table-column label="操作员名称" align="center" prop="operatorName" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:paper:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:paper:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改组卷对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="1000px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
          <el-form-item label="名称" prop="name">
            <el-input v-model="form.name" placeholder="请输入名称" />
          </el-form-item>
         <!--  <el-form-item label="总分" prop="score">
            <el-input v-model="form.score" placeholder="请输入总分" />
          </el-form-item> -->
          <el-form-item label="合格分" prop="standardScore">
            <el-input v-model="form.standardScore" placeholder="请输入合格分" />
          </el-form-item>
        <!--    <el-form-item label="发布时间" prop="createDt">
          <el-date-picker clearable size="small" style="width: 200px"
            v-model="form.createDt"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="选择发布时间">
          </el-date-picker>
        </el-form-item> -->

        <el-form-item label="状态">
          <el-radio-group v-model="form.progressCode">
            <el-radio
              v-for="dict in collegeStatusOptions"
              :key="dict.dictValue" 
              :label="parseInt(dict.dictValue)"
              >{{ dict.dictLabel }}</el-radio
            >
          </el-radio-group>
        </el-form-item>

    <!--     <el-form-item label="发布日期" prop="publishDt">
          <el-date-picker clearable size="small" style="width: 200px"
            v-model="form.publishDt"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="选择发布日期">
          </el-date-picker>
        </el-form-item> -->
        <el-form-item label="有效时间天数" prop="validityDay">
          <el-input v-model="form.validityDay" placeholder="请输入有效时间天数" />
        </el-form-item>

          <el-form :model="queryQuestionStoreParams" ref="queryQuestionStoreForm" :inline="true">
          <el-form-item  label="题型" prop="typeCode">
           <el-select v-model="queryQuestionStoreParams.typeCode"  placeholder="请选择题型">
            <el-option
              v-for="item in txOptions"
              :key="item.id"
              :label="item.label"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item> 
            <el-form-item>
              <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQueryQuestionStore">搜索</el-button>
              <el-button icon="el-icon-refresh" size="mini" @click="resetQueryQuestionStore">重置</el-button>
            </el-form-item>
          </el-form>

          <el-row>
            <el-table v-loading="loading1" ref="list"  :data="questionStoreList"  height="600px">
              <el-table-column type="selection" width="55" align="center" />
              <el-table-column label="标识" v-if="false" align="center" prop="id" />
              <el-table-column prop="typeName" label="题型"></el-table-column>
              <el-table-column prop="content" label="题面">
                <template slot-scope="scope">
                  <span v-html="scope.row.content"></span>
                </template>
              </el-table-column>
              <el-table-column prop="score" label="计分" filtered-value="0" >
              <template slot-scope="scope">
                <el-input v-model="scope.row.score" ></el-input>
              </template>
            </el-table-column>
            </el-table>
            <pagination
              v-show="questionStoreTotal>0"
              :page-sizes="[30, 50, 100]"
              :total="questionStoreTotal"
              :page.sync="queryQuestionStoreParams.pageNum"
              :limit.sync="queryQuestionStoreParams.pageSize"
              @pagination="getQuestionStoreList"
            />
          </el-row>
     <br>
     <br>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import { getquestionStore,listquestionStore,listPaper, getPaper, delPaper, addPaper, updatePaper, exportPaper } from "@/api/system/paper";

export default {
  name: "Paper",
  data() {
    return {
      // 遮罩层
      loading: true,
       // 遮罩层
      loading1: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 组卷表格数据
      paperList: [],
       //习题表格数据
      questionStoreList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 状态字典
      collegeStatusOptions: [],
      // 删除位字典
      collegeIsDeleteOptions: [],
       // 总条数
      questionStoreTotal: 0,
      //编辑习题类型
      txOptions: [{id:1,label:"判断题"},{id:2,label:"单选题"},{id:3,label:"多选题"}],
      //记录组卷已有习题
      haveList: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: null,
        score: null,
        standardScore: null,
        questionCount: null,
        createDt: null,
        progressCode: 0,
        publishDt: null,
        validityDay: null,
        operatorId: null,
        operatorCode: null,
        operatorName: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        name: [
          { required: true, message: "名称不能为空", trigger: "blur" },
        ],
        score: [
          { required: true, message: "总分不能为空", trigger: "blur" },
        ],
        standardScore: [
          { required: true, message: "合格分不能为空", trigger: "blur" },
        ],
      },
       queryQuestionStoreParams:{
        pageNum: 1,
        pageSize: 30,
        paperId: undefined,
        typeCode: undefined,
      },
    };
  },
  created() {
    this.getList();
     this.getDicts("sys_sj_state").then((response) => {
      this.collegeStatusOptions = response.data;
    });
      
  },
  methods: {
      // 状态字典翻译
    collegeStatusFormat(row, column) {
      return this.selectDictLabel(this.collegeStatusOptions, row.progressCode);
    },
    // 删除位字典翻译
    collegeIsDeleteFormat(row, column) {
      return this.selectDictLabel(
        this.collegeIsDeleteOptions,
        row.collegeIsDelete
      );
    },
    //习题重置
     resetQueryQuestionStore(){
      this.resetForm("queryQuestionStoreForm");
      this.handleQueryQuestionStore();
    },
    //搜索习题
    handleQueryQuestionStore(){
       this.queryQuestionStoreParams.pageNum = 1;
       this.getQuestionStoreList();
    },
    getQuestionStoreList() {
      this.loading1 = true;
      listquestionStore(this.queryQuestionStoreParams).then(response => {
        this.questionStoreList = response.rows;
        this.questionStoreTotal = response.total;
        this.loading1 = false;
        const list = [];
            this.haveList = [];
          var resp = this.$refs.list.selection;
          resp.forEach(item => {
            if(item.score == undefined || item.score == '') this.$set(item, 'score', '0');
            this.haveList.push(item);
          });
          // questionStoreList是数组较长的那一组，haveList是较短的那组数组,haveList是记录组卷已有的习题，如果组卷需要查找新的习题，需要将已有的习题回写进去
          for(var i=0;i<this.haveList.length;i++){
              for(var j=0;j< this.questionStoreList.length;j++){ 
                  if( this.questionStoreList[j].id == this.haveList[i].id){
                    this.questionStoreList.splice(j,1);
                    j = j - 1;
                }
              }
          }
          this.haveList.forEach(item =>{
            this.questionStoreList.push(item);
          })
          this.$nextTick(()=>{
	            this.questionStoreList.forEach(row => {
              console.log(row); // 这里仅仅加了个打印操作
              if(row.score != undefined && row.score !== ''){
              this.$refs.list.toggleRowSelection(row,true);
              }
              });
            })
      });
    },

     //查询组卷
     getListPaper() {
       listPaper(this.queryParams).then(response => {
        this.paperOptions = response.rows;
      });
    },
    /** 查询组卷列表 */
    getList() {
      this.loading = true;
      listPaper(this.queryParams).then(response => {
        this.paperList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        name: null,
        score: null,
        standardScore: null,
        questionCount: null,
        createDt: null,
        progressCode: 0,
        publishDt: null,
        validityDay: null,
        operatorId: null,
        operatorCode: null,
        operatorName: null,
        list:[]
      };
      this.resetForm("form");
      this.questionStoreList = [];
      this.questionStoreTotal = 0;
      this.queryQuestionStoreParams.typeCode = undefined
      
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加组卷";
      this.handleQueryQuestionStore();
    },
   
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      this.loading1 = true;
      getPaper(id).then(response => {
        const resp = response.data;
        this.form = response.data;
        this.open = true;
        this.title = "修改组卷";
        listquestionStore(this.queryQuestionStoreParams).then(response1 => {
        this.loading1 = false;
        const data = response1.rows;
        resp.list.forEach(item => {
          data.forEach(item1 => {
            if(item.questionStoreId == item1.id){
              item1.score = item.score;
              this.questionStoreList.push(item1);
              return false;
            }
          });
        })
         this.$refs.list.toggleAllSelection();
           this.questionStoreTotal = resp.list.length;
           this.haveList = this.questionStoreList;
        });
      });
      
      
    
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
            var resp = this.$refs.list.selection;
             var listMap = [];
             var scoreCount = 0;
            resp.forEach(item => {
              var list = {};
              list.questionStoreId = item.id;
              list.score = item.score == undefined ? this.$set(item, 'score', '0') : item.score;
              scoreCount += parseInt(item.score);
              listMap.push(list);
            });
            this.form.list = listMap;    
            this.form.score = scoreCount;
            this.form.questionCount = this.form.list.length;
          if (this.form.id != null) {
            updatePaper(this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              }
            });
          } else {
            addPaper(this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              }
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm('是否确认删除组卷编号为"' + ids + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delPaper(ids);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        }).catch(function() {});
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有组卷数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return exportPaper(queryParams);
        }).then(response => {
          this.download(response.msg);
        }).catch(function() {});
    }
  }
};
</script>
